<template>
  <el-button @click="toggleSidebar" class="toggle-sidebar-button" plain>
    <el-icon><Fold /></el-icon>
  </el-button>
  <el-breadcrumb separator="/" class="breadcrumb-container">
    <el-breadcrumb-item v-for="(item, index) in breadcrumbItems" :key="index">
      {{ item }}
    </el-breadcrumb-item>
  </el-breadcrumb>

  <div class="flex flex-wrap items-center">
    <el-dropdown>
      <div class="user-avatar-wrapper">
        <img :src="imageStore.imageUrl || defaultImageUrl" class="user-avatar" />
        <el-icon class="el-icon--right"><arrow-down /></el-icon>
      </div>
      <template #dropdown>
        <el-dropdown-menu>
          <el-dropdown-item @click="navigateTo('Home')">首页</el-dropdown-item>
          <el-dropdown-item @click="navigateTo('PersonalInfo')">个人中心</el-dropdown-item>
          <el-dropdown-item @click="logout">退出登录</el-dropdown-item>
          <el-dropdown-item class="delete-account" @click="confirmDeleteAccount">
            <el-icon><SwitchButton /></el-icon>
            注销账户
          </el-dropdown-item>
        </el-dropdown-menu>
      </template>
    </el-dropdown>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted } from 'vue'; // 确保导入了 ref 和 onMounted
import { useRoute, useRouter } from 'vue-router';
import { ElMessageBox, ElMessage } from 'element-plus';
import { ArrowDown, Fold, SwitchButton } from '@element-plus/icons-vue';
import { useImageStore } from '../store/avatarStore'; // 引入Pinia store
import userImage from '../picture/user.png'; // 使用import语句导入图片
import { UserService } from '../api/Login'; // 导入UserService

interface User {
  id: string;
  avatar: string;
  nickname: string;
  username: string;
  phone: string;
  email: string;
  department: string;
  role: string;
  gender: string;
  tags: string[];
}

const route = useRoute();
const router = useRouter();
const imageStore = useImageStore(); // 初始化store

const defaultImageUrl = userImage; // 使用简单的图片路径

const breadcrumbItems = computed(() => {
  const matchedRoutes = route.matched;
  return matchedRoutes.map(r => r.meta.title || r.name);
});

const user = ref<User>({
  id: '',
  avatar: '',
  nickname: '',
  username: '',
  phone: '',
  email: '',
  department: '',
  role: '',
  gender: '',
  tags: []
});

const navigateTo = (routeName: string) => {
  router.push({ name: routeName });
};

const logout = () => {
  ElMessageBox.confirm(
    '确定要退出登录吗?',
    '提示',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    router.push({ name: 'Login' });
   /*  UserService.logout().then(() => {
      sessionStorage.removeItem('currentUser');  // 移除用户信息
      router.push({ name: 'Login' });
    }).catch(() => {
      // 处理登出失败的情况
    }); */
  }).catch(() => {});
};

const confirmDeleteAccount = () => {
  ElMessageBox.confirm(
    '确定要注销账户吗? 该操作无法撤销!',
    '警告',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    }
  ).then(() => {
    fetchUserProfile().then(() => {
      deleteUserAccount();
    }).catch(() => {
      ElMessage.error('获取用户信息失败，无法删除账户');
    });
  }).catch(() => {});
};

const deleteUserAccount = () => {
  if (user.value && user.value.id) {
    UserService.deleteUser(user.value.id).then(() => {
      ElMessage.success('账户已注销');
      sessionStorage.removeItem('currentUser'); // 移除用户信息
      router.push({ name: 'Login' }); // 重定向到登录页面
    }).catch(() => {
      ElMessage.error('注销账户失败');
    });
  } else {
    ElMessage.error('未找到用户信息');
  }
};

const toggleSidebar = () => {
  const sidebar = document.querySelector('.sidebar-container');
  const mainContent = document.querySelector('.main-content');
  const header = document.querySelector('.fixed-header');
  if (sidebar && mainContent && header) {
    sidebar.classList.toggle('collapsed');
    mainContent.classList.toggle('expanded');
    header.classList.toggle('expanded');
  }
};

const fetchUserProfile = async () => {
  try {
    const response = await UserService.getProfile();
    if (response.data && response.data.user) {
      user.value = response.data.user;
      // 其他相关处理
    } else {
     // ElMessage.error(response.data.msg || '加载用户信息失败');
      user.value = {
        id: '',
        avatar: '',
        nickname: '',
        username: '',
        phone: '',
        email: '',
        department: '',
        role: '',
        gender: '',
        tags: []
      };
    }
  } catch (error) {
   // ElMessage.error('加载用户信息失败');
    user.value = {
      id: '',
      avatar: '',
      nickname: '',
      username: '',
      phone: '',
      email: '',
      department: '',
      role: '',
      gender: '',
      tags: []
    };
  }
};

onMounted(() => {
  fetchUserProfile();
});
</script>

<style scoped>
.toggle-sidebar-button {
  margin-right: 10px;
  border: none;
  background: none;
}

.el-breadcrumb {
  display: flex;
  align-items: center;
  background-color: #ffffff;
  padding: 0 20px;
  height: 50px;
  width: 1300px;
  margin: 0 auto; /* 确保容器居中，如果不需要可以去掉 */
}

.example-showcase .el-dropdown + .el-dropdown {
  margin-left: 15px;
}

.example-showcase .el-dropdown-link {
  cursor: pointer;
  color: var(--el-color-primary);
  display: flex;
  align-items: center;
}

.user-avatar-wrapper {
  display: flex;
  align-items: center;
  margin-top: 8px; /* 调整位置 */
}

.user-avatar {
  cursor: pointer;
  width: 35px;
  height: 35px;
  border-radius: 10px;
  margin-right: 8px;
  outline: none; /* 去掉黑框 */
}

.user-avatar:focus {
  outline: none; /* 确保选中时也没有黑框 */
}

</style>
